// 关于蛇的
(function (window) {
    var list = [];
    // 蛇类，用来实例化蛇对象
    function Snake(width, height, direction) {
        this.width = width || 20;
        this.height = height || 20;
        this.direction = direction || 'right';
        this.body = [
            {x: 3, y: 1, color:'red'},
            {x: 2, y: 1, color:'green'},
            {x: 1, y: 1, color:'blue'},
        ];
    }

    // 渲染蛇身体
    Snake.prototype.render = function (map) {
        remove();
        // 循环渲染蛇身体
        for (var i = 0; i < this.body.length; i++) {
            var unit = this.body[i];
            var div = document.createElement('div');
            div.style.width = this.width + 'px';
            div.style.height = this.height + 'px';
            div.style.position = 'absolute';
            div.style.left = unit.x * this.width + 'px';
            div.style.top = unit.y * this.height + 'px';
            div.style.backgroundColor = unit.color;
            map.appendChild(div);
            list.push(div);
        }
    }

    // 删除旧蛇
    function remove () {
        for (var i = list.length - 1; i >= 0; i--) {
            list[i].parentNode.removeChild(list[i]);
            // 保存蛇的数组里面也要删除div
            list.pop();
        }
    }

    // 蛇的移动
    Snake.prototype.move = function () {
        // 蛇身体移动
        for (var i = this.body.length - 1; i > 0; i--) {
            this.body[i].x = this.body[i - 1].x;
            this.body[i].y = this.body[i - 1].y;
        }

        // 蛇头的移动
        switch (this.direction) {
            case 'right':
                this.body[0].x++;
                break;
            case 'left':
                this.body[0].x--;
                break;
            case 'top':
                this.body[0].y--;
                break;
            case 'bottom':
                this.body[0].y++;
                break;
        }
    }

    window.Snake = Snake;
})(window)